<template>
  <j-modal :title="title" :width="800" :visible="visible" @ok="handleOk" @cancel="handleCancel" cancelText="取消" :confirmLoading="confirmLoading">
    <div class="approve-modal-content">
      <a-row :gutter="24">
        <!-- 合同基本信息展示 -->
        <a-col :span="12">
          <div class="contract-info">
            <h4>合同信息</h4>
            <a-descriptions :column="1" bordered size="small">
              <a-descriptions-item label="合同主题">{{ contractInfo.contractTheme }}</a-descriptions-item>
              <a-descriptions-item label="合同分类">{{ contractInfo.contractCategory }}</a-descriptions-item>
              <a-descriptions-item label="合同金额">{{ contractInfo.amount }}</a-descriptions-item>
              <a-descriptions-item label="签订日期">{{ contractInfo.createTime }}</a-descriptions-item>
              <a-descriptions-item label="开始日期">{{ contractInfo.startDate }}</a-descriptions-item>
              <a-descriptions-item label="结束日期">{{ contractInfo.endDate }}</a-descriptions-item>
              <a-descriptions-item label="我方代表">{{ contractInfo.myDelegate }}</a-descriptions-item>
              <a-descriptions-item label="销售人员">{{ contractInfo.salePerson }}</a-descriptions-item>
            </a-descriptions>
          </div>
        </a-col>

        <!-- 审批状态信息 -->
        <a-col :span="12">
          <div class="approve-status-info">
            <h4>审批状态</h4>
            <a-descriptions :column="1" bordered size="small">
              <a-descriptions-item label="当前状态">
                <a-tag :color="getStatusColor(contractInfo.approveStatus)" size="large">
                  {{ getStatusText(contractInfo.approveStatus) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="审批人">{{ contractInfo.approveName || '暂无' }}</a-descriptions-item>
              <a-descriptions-item label="收款状况">
                <a-tag :color="getPaymentStatusColor(contractInfo.paymentStatus)">
                  {{ getPaymentStatusText(contractInfo.paymentStatus) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="到账总额">{{ contractInfo.arriveAmount || '0' }}</a-descriptions-item>
            </a-descriptions>
          </div>
        </a-col>
      </a-row>

      <!-- 审批操作区域 -->
      <div class="approve-actions">
        <h4>审批操作</h4>
        <a-form :model="approveForm" layout="vertical">
          <a-form-item label="审批人" required>
            <a-input v-model:value="approveForm.approveName" placeholder="审批人" disabled />
          </a-form-item>
          <a-form-item label="审批结果" required>
            <a-space :size="16">
              <a-button :type="selectedOption === '2' ? 'primary' : 'default'" size="large" @click="selectOption('2')">
                <CheckCircleOutlined style="margin-right: 8px" />
                通过审批
              </a-button>
              <a-button :type="selectedOption === '3' ? 'primary' : 'default'" size="large" @click="selectOption('3')">
                <CloseCircleOutlined style="margin-right: 8px" />
                拒绝审批
              </a-button>
            </a-space>
            <div class="selection-hint" v-if="!selectedOption">
              <InfoCircleOutlined style="color: #faad14; margin-right: 8px" />
              <span style="color: #666; font-size: 14px">请选择审批结果</span>
            </div>
          </a-form-item>

          <!-- 审批通过后的项目创建选项 -->
          <a-form-item v-if="approveForm.approveStatus === '2'">
            <div class="project-creation-section">
              <div class="section-header">
                <ProjectOutlined style="color: #52c41a; margin-right: 8px" />
                <span style="font-weight: 600; color: #333">项目创建</span>
              </div>
              <div class="project-options">
                <a-checkbox v-model:checked="createProject" style="margin-bottom: 12px">
                  <span style="font-weight: 500">创建项目流入项目管理模块</span>
                </a-checkbox>
                <div v-if="createProject" class="project-form">
                  <a-input v-model:value="projectForm.projectName" placeholder="项目名称（默认使用合同名称）" style="margin-bottom: 12px" />
                  <a-textarea v-model:value="projectForm.projectDesc" placeholder="项目描述（可选）" :rows="3" :maxlength="200" show-count />
                </div>
              </div>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </j-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, defineEmits } from 'vue';

  import { CheckCircleOutlined, CloseCircleOutlined, InfoCircleOutlined, ProjectOutlined } from '@ant-design/icons-vue';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  import { approveContract, rejectContract } from '../Contracts.api';
  import { useUserStore } from '/@/store/modules/user';

  const emit = defineEmits(['register', 'success', 'cancel']);


  const userStore = useUserStore();
  const currentUserName = userStore.getUserInfo?.realname || userStore.getUserInfo?.username || '当前用户';

  const title = ref<string>('合同审批');
  const visible = ref<boolean>(false);
  const confirmLoading = ref<boolean>(false);

  // 合同信息
  const contractInfo = reactive({
    id: '',
    contractTheme: '',
    contractCategory: '',
    amount: '',
    approveStatus: '',
    approveName: '',
    createTime: '',
    startDate: '',
    endDate: '',
    myDelegate: '',
    salePerson: '',
    paymentStatus: '',
    arriveAmount: '',
  });

  // 审批表单
  const approveForm = reactive({
    approveStatus: '', // 初始为空，让用户选择
    approveName: '',
  });

  // 记录当前选中的选项，用于显示蓝色边框效果
  const selectedOption = ref<string>('');

  // 项目创建相关
  const createProject = ref<boolean>(false);
  const projectForm = reactive({
    projectName: '',
    projectDesc: '',
  });

  /**
   * 获取状态颜色
   */
  function getStatusColor(status: string) {
    const colorMap = {
      '1': 'orange',
      '2': 'green',
      '3': 'red',
    };
    return colorMap[status] || 'default';
  }

  /**
   * 获取状态文本
   */
  function getStatusText(status: string) {
    const textMap = {
      '1': '待审批',
      '2': '已审批',
      '3': '已拒绝',
    };
    return textMap[status] || '未知';
  }

  /**
   * 获取收款状态颜色
   */
  function getPaymentStatusColor(status: string) {
    const colorMap = {
      '1': 'red',
      '2': 'orange',
      '3': 'green',
    };
    return colorMap[status] || 'default';
  }

  /**
   * 获取收款状态文本
   */
  function getPaymentStatusText(status: string) {
    const textMap = {
      '1': '未付款',
      '2': '部分付款',
      '3': '已付款',
    };
    return textMap[status] || '未知';
  }

  /**
   * 选择审批选项
   */
  function selectOption(value: string) {
    selectedOption.value = value;
    approveForm.approveStatus = value;

    if (value === '3') {
      // 如果选择了拒绝，取消项目创建选项
      createProject.value = false;
    } else if (value === '2') {
      // 如果选择了通过，自动填充项目名称
      if (!projectForm.projectName) {
        projectForm.projectName = contractInfo.contractTheme || '';
      }
    }
  }

  /**
   * 打开审批模态框
   */
  function open(record: any) {
    console.log('ContractApproveModal open method called with record:', record);
    visible.value = true;
    console.log('Modal visible set to:', visible.value);
    // 复制合同信息
    Object.assign(contractInfo, record);
    // 重置审批表单，不预设任何选项
    approveForm.approveStatus = '';
    approveForm.approveName = currentUserName;
    selectedOption.value = '';
    // 重置项目创建相关
    createProject.value = false;
    projectForm.projectName = '';
    projectForm.projectDesc = '';
    console.log('Modal setup completed');
  }

  /**
   * 确定按钮点击事件
   */
  async function handleOk() {
    if (!approveForm.approveStatus) {
      return;
    }

    try {
      confirmLoading.value = true;

      if (approveForm.approveStatus === '2') {
        // 通过审批
        const approveData = {
          approveStatus: approveForm.approveStatus,
          approveName: approveForm.approveName || currentUserName,
        };

        console.log('准备调用通过审批接口:', {
          contractId: contractInfo.id,
          approveData,
          contractInfo,
        });

        const res = await approveContract(contractInfo.id, approveData);

        if (res.success) {
          // 如果选择创建项目，则创建项目
          if (createProject.value) {
            try {
              await createProjectFromContract();
            } catch (error) {
              console.error('项目创建失败：', error);
            }
          }

          // 传递审批结果信息，包括是否需要创建项目
          emit('success', {
            approveStatus: approveForm.approveStatus,
            needCreateProject: !createProject.value,
            contractInfo: contractInfo,
          });

          handleCancel();
        } else {
        }
      } else if (approveForm.approveStatus === '3') {
        // 拒绝审批
        const rejectData = {
          approveStatus: approveForm.approveStatus,
          approveName: approveForm.approveName || currentUserName,
        };

        console.log('准备调用拒绝审批接口:', {
          contractId: contractInfo.id,
          rejectData,
          contractInfo,
        });

        const res = await rejectContract(contractInfo.id, rejectData);

        if (res.success) {

          // 传递审批结果信息
          emit('success', {
            approveStatus: approveForm.approveStatus,
            needCreateProject: false,
            contractInfo: contractInfo,
          });

          handleCancel();
        } else {
        }
      }
    } catch (error) {
      console.error('审批操作出错：', error);
    } finally {
      confirmLoading.value = false;
    }
  }

  /**
   * 从合同创建项目
   */
  async function createProjectFromContract() {
    const projectData = {
      projectName: projectForm.projectName || contractInfo.contractTheme,
      projectDesc: projectForm.projectDesc || `基于合同"${contractInfo.contractTheme}"创建的项目`,
      contractId: contractInfo.id,
      contractTheme: contractInfo.contractTheme,
      amount: contractInfo.amount,
      startDate: contractInfo.startDate,
      endDate: contractInfo.endDate,
      status: '1', // 项目状态：1-进行中
      createTime: new Date().toISOString(),
    };

    // 这里应该调用项目创建的API
    // 由于还没有项目模块的API，我们先模拟一下
    console.log('创建项目数据：', projectData);

    // TODO: 调用项目创建API
    // const res = await createProject(projectData);
    // if (!res.success) {
    //   throw new Error(res.message || '项目创建失败');
    // }
  }

  /**
   * 取消按钮回调事件
   */
  function handleCancel() {
    visible.value = false;
    emit('cancel');
  }

  defineExpose({
    open,
    visible,
  });
</script>

<style>
  /**隐藏样式-modal确定按钮 */
  .jee-hidden {
    display: none !important;
  }
</style>
<style lang="less" scoped>
  .approve-modal-content {
    padding: 0 20px;

    .contract-info,
    .approve-status-info {
      h4 {
        margin-bottom: 16px;
        color: #1890ff;
        font-weight: 600;
        font-size: 16px;
        border-left: 4px solid #1890ff;
        padding-left: 12px;
      }

      :deep(.ant-descriptions) {
        .ant-descriptions-item-label {
          font-weight: 500;
          color: #666;
          width: 100px;
        }

        .ant-descriptions-item-content {
          color: #333;
        }
      }
    }

    .approve-actions {
      margin-top: 24px;
      padding-top: 24px;
      border-top: 1px solid #f0f0f0;

      h4 {
        margin-bottom: 16px;
        color: #1890ff;
        font-weight: 600;
        font-size: 16px;
        border-left: 4px solid #1890ff;
        padding-left: 12px;
      }

      :deep(.ant-form-item-label) {
        font-weight: 500;
        color: #666;
      }

      // 选择提示样式
      .selection-hint {
        margin-top: 16px;
        padding: 12px 16px;
        background: linear-gradient(135deg, #fffbe6, #fff7e6);
        border: 1px solid #ffe58f;
        border-radius: 8px;
        display: flex;
        align-items: center;
      }

      // 项目创建部分样式
      .project-creation-section {
        margin-top: 16px;
        padding: 16px;
        background: linear-gradient(135deg, #f6ffed, #e6f7ff);
        border: 1px solid #b7eb8f;
        border-radius: 8px;

        .section-header {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          font-size: 14px;
        }

        .project-options {
          .project-form {
            margin-top: 12px;
            padding: 12px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 6px;
            border: 1px solid #d9d9d9;
          }
        }
      }
    }

    :deep(.ant-input) {
      border-radius: 6px;

      &:focus {
        border-color: #1890ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }
    }
  }

  :deep(.ant-tag) {
    font-weight: 500;
    padding: 4px 12px;
    border-radius: 4px;
  }
</style>
